package com.whoami.dataplatform.tag_combine.hbase.rw;

import com.google.common.collect.Lists;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Random;

/**
 * @author tzp
 * @since 2019/8/12
 */
public class TableWrite {
    private static final String TABLE_NAME = "test_java";
    private static final String CF_DEFAULT = "cf1";

    public static void main(String[] args) throws IOException {
        Configuration config = HBaseConfiguration.create();
        config.addResource(new Path(System.getenv("HBASE_CONF_DIR") + "/conf", "hbase-site.xml"));
        batchPut1(config);
    }

    public static void put(Configuration config) throws IOException {
        try (Connection connection = ConnectionFactory.createConnection(config)) {
            TableName tableName = TableName.valueOf(TABLE_NAME);
            Table table = connection.getTable(tableName);
            Put put = new Put("row1".getBytes());
            put.addColumn(CF_DEFAULT.getBytes(), null, "heihei".getBytes());
            table.put(put);
            table.close();
        }
    }

    public static void batchPut1(Configuration config) throws IOException {
        try (Connection connection = ConnectionFactory.createConnection(config)) {
            TableName tableName = TableName.valueOf(TABLE_NAME);
            Table table = connection.getTable(tableName);

            Random random = new Random();

            ArrayList<Put> puts = Lists.<Put>newArrayList();
            for (int i = 0; i < 100; i++) {
                Put put = new Put(("row" + i).getBytes());
                put.addColumn(CF_DEFAULT.getBytes(), "ct".getBytes(),
                        Bytes.toBytes(random.nextInt(100)));
                puts.add(put);
            }
            table.put(puts);
            table.close();
        }
    }

    public static void batchPut(Configuration config) throws IOException {
        try (Connection connection = ConnectionFactory.createConnection(config)) {
            TableName tableName = TableName.valueOf(TABLE_NAME);
            Table table = connection.getTable(tableName);

            BitSet bitSet = new BitSet(1000);
            Random random = new Random();

            for (int i = 0; i < 100; i++) {
                bitSet.clear();
                bitSet.set(random.nextInt(1000));
                bitSet.set(random.nextInt(1000));
                bitSet.set(random.nextInt(1000));
            }
        }
    }

}
